<template>
    <div class="order-cost-form">
        <div style="margin: 20px;">
            <el-form ref="forms" :rules="rules" :model="form" label-width="150px">
                <el-form-item label="负责人" prop="directorIds">
                    <el-select v-model="form.directorIds" placeholder="请选择负责人" filterable
                        @change="changeChooseBusinessId"
                        :disabled="(userInfo.role && (userInfo.role.includes(40) || userInfo.role.includes(55))) || isChange">
                        <el-option v-for="(item,index) in businessList" :key="index" :label="item.username"
                            :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="部门" prop="departId">
                    <el-select v-model="form.departId" placeholder="请选择部门"
                        :disabled="userInfo.role && (userInfo.role.includes(40) || userInfo.role.includes(55))">
                        <el-option v-for="(item,index) in departList" :key="index" :label="item.sysValueName"
                            :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="公司名称" prop="companyName">
                    <div style="width: 400px;">
                        <el-input v-model="form.companyName"></el-input>
                    </div>
                </el-form-item>
                <el-form-item label="对接品牌名称" prop="brandsName">
                    <div style="display: flex;">
                        <div style="width: 400px;">
                            <el-input v-model="form.brandsName" @input="getHas"></el-input>
                        </div>
                        <el-popover placement="top" title="" width="250" trigger="hover">
                            <div style="white-space: pre-wrap;">{{ brandsRemark }}</div>
                            <div style="display: flex; justify-content: center;width: 25px;margin: 10px"
                                slot="reference">
                                <i class="el-icon-question"></i>
                            </div>
                        </el-popover>
                        <div style="width: 400px;display: flex;padding-left: 20px;" v-if="form.brandsName && isGetHas">
                            <div style="display: flex;" v-if="isGetHas == 2">
                                该品牌已存在，并且受保护
                            </div>
                            <div style="display: flex;" v-if="isGetHas == 3">
                                该品牌已存在，并且不受保护
                            </div>
                            <div style="display: flex;" v-if="isGetHas == 1">
                                该品牌不存在，可以{{isChange ? '修改' : '添加'}}
                            </div>
                            <div style="display: flex;" v-if="isGetHas == 4">
                                <i class="el-icon-loading"></i>
                            </div>
                        </div>
                    </div>
                </el-form-item>
                <el-form-item label="对接人姓名" prop="contactPersonName">
                    <div style="width: 400px;">
                        <el-input v-model="form.contactPersonName"></el-input>
                    </div>
                </el-form-item>
                <el-form-item label="对接人岗位" prop="contactPersonPost">
                    <div style="width: 400px;">
                        <el-input v-model="form.contactPersonPost"></el-input>
                    </div>
                </el-form-item>
                <el-form-item label="对接人联系方式" prop="contactPersonTelList">
                    <div style="width: 600px;">
                        <div v-for="(item,index) in form.contactPersonTelList" :key="index"
                            :style="'display: flex;' + (index > 0 ? 'padding-top: 10px;' : '')">
                            <div style="width: 100px;">
                                <el-select v-model="item.type" placeholder="请选择客户状态">
                                    <el-option v-for="(telItem,telIndex) in telTypeList" :key="telIndex"
                                        :label="telItem.sysValueName" :value="telItem.id"></el-option>
                                </el-select>
                            </div>
                            <div style="padding-left: 10px;">
                                <el-input v-model="item.tel"></el-input>
                            </div>
                            <div style="padding-left: 10px;"
                                v-if="index == form.contactPersonTelList.length - 1 && index < 9">
                                <el-button type="success" icon="el-icon-plus" circle @click="addTel(index)"></el-button>
                            </div>
                            <div style="padding-left: 10px;" v-if="form.contactPersonTelList.length > 1">
                                <el-button type="danger" icon="el-icon-delete" circle
                                    @click="removeTel(index)"></el-button>
                            </div>
                        </div>
                    </div>
                </el-form-item>
                <el-form-item label="省市区" prop="customerArea">
                    <div style="width: 400px;display: flex;">
                        <el-select v-model="form.customerProvince" @change="getCityList" placeholder="请选择省">
                            <el-option v-for="(item,index) in provinceList" :key="index" :label="item"
                                :value="item"></el-option>
                        </el-select>
                        <div style="padding-left: 20px;"></div>
                        <el-select v-model="form.customerCity" @change="getDistrictList" placeholder="请选择市"
                            v-if="form.customerProvince">
                            <el-option v-for="(item,index) in cityList" :key="index" :label="item"
                                :value="item"></el-option>
                        </el-select>
                        <div style="padding-left: 20px;"></div>
                        <el-select v-model="form.customerArea" placeholder="请选择区" v-if="form.customerCity">
                            <el-option v-for="(item,index) in districtList" :key="index" :label="item"
                                :value="item"></el-option>
                        </el-select>
                    </div>
                </el-form-item>
                <!-- <el-form-item label="客户状态" prop="customerStatus">
                    <el-select v-model="form.customerStatus" placeholder="请选择客户状态">
                        <el-option
                            v-for="(item,index) in customerStatusList"
                            :key="index"
                            :label="item.sysValueName"
                            :value="item.id"
                        ></el-option>
                    </el-select>
                </el-form-item> -->
                <el-form-item label="客户来源" prop="customerSource">
                    <el-select v-model="form.customerSource" placeholder="请选择客户来源">
                        <el-option v-for="(item,index) in customerSourceList" :key="index" :label="item.sysValueName"
                            :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="客户阶段" prop="customerStage">
                    <el-select v-model="form.customerStage" placeholder="请选择客户阶段">
                        <el-option v-for="(item,index) in customerStageList" :key="index" :label="item.sysValueName"
                            :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="客户产品类型" prop="customerProductType">
                    <el-select v-model="form.customerProductType" placeholder="请选择客户产品类型">
                        <el-option v-for="(item,index) in customerProductTypeList" :key="index"
                            :label="item.sysValueName" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="客户网上旗舰店" prop="customerOnlineShop">
                    <div style="width: 400px;">
                        <el-input v-model="form.customerOnlineShop"></el-input>
                    </div>
                </el-form-item>
                <el-form-item label="旗舰店粉丝量" prop="fans">
                    <div style="width: 400px;">
                        <el-input v-model="form.fans"></el-input>
                    </div>
                </el-form-item>
                <el-form-item label="客户类型" prop="customerType">
                    <el-select v-model="form.customerType" placeholder="请选择客户类型">
                        <el-option v-for="(item,index) in customerTypeList" :key="index" :label="item.sysValueName"
                            :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="客户地址">
                    <div style="width: 400px;">
                        <el-input v-model="form.customerAddress"></el-input>
                    </div>
                </el-form-item>
                <el-form-item label="公司规模">
                    <div style="width: 400px;">
                        <el-input v-model="form.companyScale" placeholder="旗舰店粉丝数"></el-input>
                    </div>
                </el-form-item>
                <el-form-item label="协同人">
                    <el-select v-model="form.collaboratorIdList" placeholder="请选择协同人" multiple>
                        <el-option v-for="(item,index) in businessList" :key="index" :label="item.username"
                            :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="客户级别">
                    <el-select v-model="form.customerLevel" placeholder="请选择客户级别">
                        <el-option v-for="(item,index) in customerLevelList" :key="index" :label="item.sysValueName"
                            :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="重要程度">
                    <el-rate v-model="form.importanceRate" allow-half></el-rate>
                </el-form-item>
                <el-form-item label="备注">
                    <div style="width: 400px;">
                        <el-input v-model="form.remark"></el-input>
                    </div>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="onSubmit" :loading="submitLoading" :disabled="isGetHas && isGetHas == 2">{{isChange ? "修改"
                        : "立即创建"}}</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script>
import APISysLabel from "@/api/apiSysLabel";
import APIBusinessAccount from "@/api/apiBusinessAccount";
import APIBusiness from "@/api/apiBusiness";

export default {
    name: "EditProject",
    components:{
    },
    props: {
        operationList: Array,
        isShow: Boolean,
    },
    watch: {
    },
    data() {
        var validateContactPersonTelList = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入联系方式'));
            } else {
                if (this.form.contactPersonTelList.length > 0) {
                    let hasAdd = false
                    this.form.contactPersonTelList.forEach(item => {
                        if(item.tel){
                            hasAdd = true;
                        }
                    })
                    if(hasAdd){
                        // this.$refs.form.validateField('contactPersonTelList');
                        callback();
                    }else{
                        callback(new Error('请输入联系方式'));
                    }
                }else{
                    callback(new Error('请输入联系方式'));
                }
            }
        };
        return {
            showNumTest: 1,
            userInfo: {},
            chooseId: null,
            customerStatusList: [],
            customerStageList: [],
            customerTypeList: [],
            customerProductTypeList: [],
            customerLevelList: [],
            customerSourceList: [],
            businessList: [],
            form: {
                businessId: null,
                departId: null,
                companyName: null,
                companyScale: null,
                brandsName: null,
                contactPersonName: null,
                contactPersonPost: null,
                contactPersonTelList: [
                    {
                        type: 492,
                        tel: '',
                    }
                ],
                contactPersonTel: null,
                customerAddress: null,
                customerStatus: null,
                customerStage: null,
                directorIds: null,
                collaboratorIdList: null,
                customerType: null,
                customerProductType: null,
                customerLevel: null,
                importanceRate: null,
                customerSource: null,
                customerOnlineShop: null,
                fans: null,
                remark: null,
                customerProvince: null,
                customerCity: null,
                customerArea: null,
            },
            rules: {
                brandsName: [
                    { required: true, message: '请输入品牌名称', trigger: 'blur' },
                    { min: 2, message: '长度超过 2 个字符', trigger: 'blur' },
                ],
                directorIds: {
                    required: true, message: '请选择负责人', trigger: 'change'
                },
                departId: {
                    required: true, message: '请选择部门', trigger: 'change'
                },
                companyName: [
                    { required: true, message: '请输入公司名称', trigger: 'blur' },
                    { min: 1, message: '长度超过 1 个字符', trigger: 'blur' },
                ],
                contactPersonName: [
                    { required: true, message: '请输入对接人姓名', trigger: 'blur' },
                    { min: 1, message: '长度超过 1 个字符', trigger: 'blur' },
                ],
                contactPersonPost: [
                    { required: true, message: '请输入对接人岗位', trigger: 'blur' },
                    { min: 1, message: '长度超过 1 个字符', trigger: 'blur' },
                ],
                contactPersonTelList: [
                    { required: true, validator: validateContactPersonTelList, trigger: 'change' }
                ],
                customerStatus: {
                    required: true, message: '请选择客户状态', trigger: 'change'
                },
                customerStage: {
                    required: true, message: '请选择客户阶段', trigger: 'change'
                },
                customerArea: {
                    required: true, message: '请选择省市区', trigger: 'change'
                },
                // customerType: {
                //     required: true, message: '请选择客户类型', trigger: 'change'
                // },
                customerSource: {
                    required: true, message: '请选择客户来源', trigger: 'change'
                },
                customerProductType: {
                    required: true, message: '请选择客户产品类型', trigger: 'change'
                },
                customerOnlineShop: {
                    required: true, message: '请输入客户网上旗舰店', trigger: 'blur'
                },
                fans: {
                    required: true, message: '请输入旗舰店粉丝量', trigger: 'blur'
                },
            },
            departList: [],
            isChange: false, // false 新增，true 修改
            telTypeList: [],
            provinceList: [],
            cityList: [],
            districtList: [],
            isGetHas: null, // 是否受保或者有无数据，1、无数据，2、受保，3、不受保
            brandsRemark: null, // 品牌备注
            submitLoading: false,
        };
    },
    activated() {
        this.submitLoading = false
        this.isGetHas = null
        this.userInfo = JSON.parse(localStorage.getItem("mujinguserInfo"))
        this.$refs["forms"].resetFields();
        this.getProvinceList()
        this.getSysList()
        this.getBusinessList()
        this.isChange = false
        const businessAccountId = this.$route.query.businessAccountId;
        if(businessAccountId){
            this.getMsg()
            this.isChange = true
            this.getCityList()
            this.getDistrictList()
        }else{
            this.form = {
                businessId: null,
                departId: null,
                companyName: null,
                companyScale: null,
                brandsName: null,
                contactPersonName: null,
                contactPersonPost: null,
                contactPersonTelList: [
                    {
                        type: 492,
                        tel: '',
                    }
                ],
                contactPersonTel: null,
                customerAddress: null,
                customerStatus: null,
                customerStage: null,
                directorIds: null,
                collaboratorIdList: null,
                customerType: null,
                customerProductType: null,
                customerLevel: null,
                importanceRate: null,
                customerSource: null,
                customerOnlineShop: null,
                fans: null,
                remark: null,
                customerProvince: null,
                customerCity: null,
                customerArea: null,
            }
            if (this.userInfo && this.userInfo.role && (this.userInfo.role.includes(40) || this.userInfo.role.includes(55))){
                this.form.directorIds = this.userInfo.userId
            }
        }
    },
    created() {
    },
    methods: {
        getHas(val){
            if(!this.form.brandsName || !val){
                return
            }
            this.isGetHas = 4
            const params = {
                token: this.$store.state.token,
                brandsName: this.form.brandsName
            };
            if(this.isChange && this.$route.query.businessAccountId){
                params.businessAccountId = Number(this.$route.query.businessAccountId)
            }
            APIBusinessAccount.doGetBusinessAccountHas(params).then((res) => {
                if (res.key === 1000) {
                    res = res.result;
                    this.isGetHas = res.data
                }
            });
        },
        getProvinceList(){
            const params = {
                token: this.$store.state.token,
            };
            APISysLabel.get_province(params).then((res) => {
                if (res.key === 1000) {
                    res = res.result;
                    this.provinceList = res.list
                }
            });
        },
        getCityList(){
            const params = {
                token: this.$store.state.token,
                province: this.form.customerProvince
            };
            APISysLabel.get_city(params).then((res) => {
                if (res.key === 1000) {
                    res = res.result;
                    this.cityList = res.data
                }
            });
        },
        getDistrictList(){
            const params = {
                token: this.$store.state.token,
                city: this.form.customerCity
            };
            APISysLabel.get_district(params).then((res) => {
                if (res.key === 1000) {
                    res = res.result;
                    this.districtList = res.list
                }
            });
        },
        changeChooseBusinessId(val){
            this.businessList.forEach(item => {
                if(item.id == val){
                    this.form.departId = item.departId
                }
            })
        },
        addTel(){
            this.form.contactPersonTelList.push({
                type: 492,
                tel: '',
            })
        },
        removeTel(index){
            this.form.contactPersonTelList.splice(index,1)
        },
        getMsg(){
            const params = {
                token: this.$store.state.token,
                businessAccountId: this.$route.query.businessAccountId
            };
            APIBusinessAccount.getBusinessAccountMsg(params).then((res) => {
                if (res.key === 1000) {
                    res = res.result;
                    let data = res.data
                    if(data.directorIds && typeof data.directorIds ==='string'){
                        data.directorIds = parseInt(data.directorIds)
                    }
                    if(data.collaboratorIds && typeof data.collaboratorIds ==='string'){
                        let collaboratorIdList = data.collaboratorIds.split(",")
                        let list = []
                        collaboratorIdList.forEach(item => {
                            list.push(parseInt(item))
                        })
                        data.collaboratorIdList = list
                    }
                    if(data.contactPersonTel){
                        let contactPersonTelList = []
                        JSON.parse(data.contactPersonTel).forEach(item => {
                            contactPersonTelList.push({
                                type: item.type,
                                tel: item.tel,
                            })
                        })
                        data.contactPersonTelList = contactPersonTelList
                    }else{
                        data.contactPersonTelList = [{
                            type: 492,
                            tel: '',
                        }]
                    }
                    this.form = data
                }
            });
        },
        getBusinessList() {
            const params = {
                token: this.$store.state.token,
            };
            APIBusiness.getBusinessList(params).then((res) => {
                if (res.key === 1000) {
                    res = res.result;
                    this.businessList = res.list
                    if (this.form.directorIds || (this.userInfo && this.userInfo.role && (this.userInfo.role.includes(40) || this.userInfo.role.includes(55)))){
                        let directorIds = this.form.directorIds ? this.form.directorIds : this.userInfo.userId
                        this.businessList.forEach(item => {
                            if(item.id == directorIds){
                                this.form.departId = item.departId
                            }
                        })
                    }
                }
            });
        },
        getSysList() {
            const params = {
                token: this.$store.state.token,
                sysLabelIds: "23,24,25,26,27,28,29,30,32,36",
            };
            APISysLabel.getSysLabelValueManageList(params).then((res) => {
                if (res.key === 1000) {
                    res = res.result;
                    if(res.data){
                        this.telTypeList = res.data[23]
                        this.customerStatusList = res.data[24]
                        this.customerStageList = res.data[25]
                        this.customerTypeList = res.data[26]
                        this.customerProductTypeList = res.data[27]
                        this.customerLevelList = res.data[28]
                        this.customerSourceList = res.data[29]
                        this.departList = res.data[32]
                        this.brandsRemark = res.data[36][0].desc
                    }
                }
            });
        },
        formatterTime(time) {
            return this.$moment(time).format("YYYY-MM-DD HH:mm:ss");
        },
        onSubmit(){
            this.submitLoading = true
            const params = this.form;
            if(params.collaboratorIdList){
                params.collaboratorIds = params.collaboratorIdList.join(',')
            }
            if(params.contactPersonTelList){
                let list = []
                params.contactPersonTelList.forEach(item => {
                    if(item.tel){
                        list.push({
                            type: item.type,
                            tel: item.tel,
                        })
                    }
                })
                if(list.length > 0){
                    params.contactPersonTel = JSON.stringify(list)
                }
            }
            this.$refs["forms"].validate((valid) => {
                if (valid) {
                    if(!this.isChange){
                        APIBusinessAccount.doAddBusinessAccount(params).then((res) => {
                            if (res.key === 1000) {
                                this.$message({
                                    message: '提交成功',
                                    type: 'success'
                                });
                                this.$router.back()
                            }
                        });
                    }else{
                        params.id = this.$route.query.businessAccountId
                        APIBusinessAccount.doEditBusinessAccount(params).then((res) => {
                            if (res.key === 1000) {
                                this.$message({
                                    message: '修改成功',
                                    type: 'success'
                                });
                                this.$router.back()
                            }
                        });
                    }
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
    },
};
</script>
<style scoped>
.el-input-number{
    width: 250px !important;
}
.show_project{
    display: flex;
    justify-content: center;
    margin-top: 20px;
    width: 100%;
}
.show_project_msg{
    width: 90%;
}
</style>
<style lang="sass" scoped>
.order-cost-form
    background-color: white
    .cost_item_solid
        border-bottom: 1px solid #e3e3e3
    .cost_item
        width: 95%
        display: flex
        .adjustOrderItem
            margin: 20px auto
            padding-left: 40px
            display: flex
            width: 100%
            .adjustOrderItem_left
                width: 100px
                margin: 11px auto
            .adjustOrderItem_right
                width: 80%
                .show_text
                    margin: 11px auto
    .cost-footer
        padding-left: 100px
        padding-top: 50px
</style>
